package com.lemon.springboot.controller;

import com.lemon.springboot.dao.ICpuDao;
import com.lemon.springboot.dao.IMachineDao;
import com.lemon.springboot.entity.AccountVo;
import com.lemon.springboot.entity.CpuVo;
import com.lemon.springboot.entity.MachineVo;
import com.lemon.springboot.entity.Result;
import com.lemon.springboot.service.ICpuPageService;
import com.lemon.springboot.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author liuli
 * @Date 2020/12/17 5:47
 *
 * cpu详情信息
 */
@Controller
public class CpuController {
    private static Logger logger = LoggerFactory.getLogger(CpuController.class);

    @Autowired
    IMachineDao machineDao;

    @Autowired
    ICpuDao cpuDao;

    @Autowired
    ICpuPageService cpuPageService;

    @RequestMapping("/cpu")
    public String cpu(HttpServletRequest request, Model model) {
        List<MachineVo> machineVoList = machineDao.findMachineByAcc(((AccountVo) request.getSession().getAttribute("account")).getAccount());
        if (machineVoList != null && machineVoList.size() > 0) {
            model.addAttribute("machineVoList", machineVoList);
        }
        return "apm-cpu";
    }

    @RequestMapping(path = "/cpuData", method = RequestMethod.POST)
    public @ResponseBody Result cpuData(@RequestBody Map<String, String> parameter){
        Result result = new Result();
        try {
            String datetime = parameter.get("datetime");
            String token = parameter.get("token");
            Date endTime = DateUtil.dateFormat("yyyy-MM-dd HH:mm").parse(datetime);
            Date startTime = new Date(endTime.getTime() - DateUtil._30MINI); // 30分钟的时间间隔
            int maxDataCount = ((int) (DateUtil._30MINI / DateUtil._30SEC));
            Map<String, Object> cpuData = cpuPageService.findCpuDataByDate(startTime, endTime, token, maxDataCount);
            result.setCodeAndMessage("200", "success").setData(cpuData);
            return result;
        } catch (Exception e) {
            result.setCodeAndMessage("500", e.getMessage());
            logger.error("findCpuData error.",e);
        }
        return result;
    }
}
